package tails

import (
	"context"
	"encoding/json"
	"github.com/hpcloud/tail"
	"github.com/sirupsen/logrus"
)

var (
	TailTask        []*tailTask
	TailTaskContext context.Context
	TailTaskCancel  context.CancelFunc
	tailConfig      tail.Config
)

type tailTask struct {
	Tail  *tail.Tail
	Path  string `json:"path"`
	Topic string `json:"topic"`
}

func InitTailTask(fileList string) error {
	var err error
	err = json.Unmarshal([]byte(fileList), &TailTask)
	if err != nil {
		logrus.Error("json convert defeat!", fileList)
		return err
	}
	// 启动上下文控制追踪文件Goroutine
	TailTaskContext, TailTaskCancel = context.WithCancel(context.Background())
	tailConfig := tail.Config{
		ReOpen:    true,
		Follow:    true,
		Location:  &tail.SeekInfo{Offset: 0, Whence: 2},
		MustExist: false,
		Poll:      true,
	}
	for _, task := range TailTask {
		t, err := tail.TailFile(task.Path, tailConfig)
		task.Tail = t
		if err != nil {
			return err
		}
	}
	return nil
}
